import { forwardRef } from 'react';
import { useSafeState, useMemoizedFn } from 'ahooks';
import { cloneElement, useImperativeHandle } from 'react';
import Dialog from '../Dialog';
import { type TriggerDialogProps, TriggerDialogRefs } from './types';

const TriggerDialog = forwardRef<TriggerDialogRefs, TriggerDialogProps>((props, ref) => {
  const { children, trigger } = props;
  const [open, setOpen] = useSafeState(false);
  const openDialog = useMemoizedFn(() => setOpen(true));
  const closeDialog = useMemoizedFn(() => setOpen(false));

  useImperativeHandle(ref, () => {
    return { closeDialog };
  });

  return (
    <>
      {cloneElement(trigger, {
        onPressIn: openDialog
      })}
      <Dialog
        open={open}
        children={children}
        onClose={closeDialog}
      />
    </>
  );
})

export default TriggerDialog;